﻿using Center.Model;
using Dapper;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.Data.SqlClient;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace Center.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class AuthoizeController : ControllerBase
    {
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="account"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Login(string account, string pwd)
        {
            
            using (SqlConnection sqlConnection = new SqlConnection("Data Source=rm-cn-zv23ply3700016qo.sqlserver.rds.aliyuncs.com, 1433;Initial Catalog=WMS;User ID=wms_s123;Password=Lzb123456;Encrypt=False;"))
            {
                var aa = PasswordHasher.HashPassword(pwd);
                string sql = $"select * from  Sys_User where U_UserAccount='{account}' and U_UPwd='{aa}'";
                // 根据用户名和密码从数据库中查询用户
                User user= sqlConnection.QueryFirst<User>(sql);
                if (user != null)
                {
                    // 创建传递的数据
                    // 创建传递的数据
                    Claim[] claims = new Claim[]
                    {
                        new Claim("UUid", user.U_UId.ToString()),
                         new Claim("UUserName", user.U_UserName),
                         new Claim("UUpwd", user.U_UPwd),
                         new Claim("UUimg", user.U_UImg)
                    };

                    // 产生token
                    SymmetricSecurityKey key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("SDMC-CJAS1-SAD-DFSFA-SADHJVF-VFSS"));
                    // 产生加密对象
                    SigningCredentials signingCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
                    JwtSecurityToken jwtSecurityToken = new JwtSecurityToken(
                        issuer: "http://localhost:5259",
                        audience: "http://localhost:5084",
                        claims: claims,
                        expires: DateTime.Now.AddMinutes(20),
                        signingCredentials: signingCredentials
                    );
                    var token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
                    return new JsonResult(token);
                }
                else
                {
                    return Content("用户名或密码错误");
                }
            }
        }

    }
}
